package com.joinway.framework.support.audit;

import java.lang.reflect.Method;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.joinway.framework.core.utils.AopHelper;
import com.joinway.framework.support.audit.provider.IMonitoredMethodProvider;

public class PerformanceAspect {

	private final static Logger log = LoggerFactory.getLogger("PerformanceMonitor");
	
	protected List<IMonitoredMethodProvider> providers;
	
	public Object doAround(ProceedingJoinPoint point) throws Throwable {
		long startTime = System.currentTimeMillis();
		
		Object value = null;
		
		try{
			value = point.proceed(point.getArgs());
		}finally{
			
			if(CollectionUtils.isNotEmpty(providers) && providers.stream().anyMatch(p -> p.isTarget(point))){
				Method method = AopHelper.getMethod(point);
				long endTime = System.currentTimeMillis();
				long cost = endTime - startTime;
				log.info("{} ms was cost by {}", cost, point.getTarget().getClass().getCanonicalName() + "." + method.getName());
			}
		}
		
		return value;

	}

	public List<IMonitoredMethodProvider> getProviders() {
		return providers;
	}

	public void setProviders(List<IMonitoredMethodProvider> providers) {
		this.providers = providers;
	}

}
